<?php
class Vistec_Lightspeed_AdminController extends Mage_Adminhtml_Controller_Action
{
	protected $_stores;
	
	
	public function importAction()
    {
        #$this->loadLayout();

        #$this->_setActiveMenu('system/convert');

        #$this->_addContent(
        #    $this->getLayout()->createBlock('adminhtml/system_convert_profile_run')
        #);
        $this->getResponse()->setBody($this->getLayout()->createBlock('lightspeed/import')->toHtml());
        $this->getResponse()->sendResponse();

        #$this->renderLayout();
    }
    
	public function importallAction()
    {
        #$this->loadLayout();

        #$this->_setActiveMenu('system/convert');

        #$this->_addContent(
        #    $this->getLayout()->createBlock('adminhtml/system_convert_profile_run')
        #);
        $this->getResponse()->setBody($this->getLayout()->createBlock('lightspeed/importall')->toHtml());
        $this->getResponse()->sendResponse();

        #$this->renderLayout();
    }
    
	public function updateAction()
    {
        #$this->loadLayout();

        #$this->_setActiveMenu('system/convert');

        #$this->_addContent(
        #    $this->getLayout()->createBlock('adminhtml/system_convert_profile_run')
        #);
        $this->getResponse()->setBody($this->getLayout()->createBlock('lightspeed/update')->toHtml());
        $this->getResponse()->sendResponse();

        #$this->renderLayout();
    }
    
	public function updateallAction()
    {
        #$this->loadLayout();

        #$this->_setActiveMenu('system/convert');

        #$this->_addContent(
        #    $this->getLayout()->createBlock('adminhtml/system_convert_profile_run')
        #);
        $this->getResponse()->setBody($this->getLayout()->createBlock('lightspeed/updateall')->toHtml());
        $this->getResponse()->sendResponse();

        #$this->renderLayout();
    }
	
	public function batchRunAction()
    {
        if ($this->getRequest()->isPost()) {
            $batchId = $this->getRequest()->getPost('batch_id',0);
            $rowIds  = $this->getRequest()->getPost('rows');

            /* @var $batchModel Mage_Dataflow_Model_Batch */

            if (!is_array($rowIds) || count($rowIds) < 1) {
                //exit
                return ;
            }

            $errors = array();
            $messages = array();
            $saved  = 0;
			$batchModel = Mage::getModel('lightspeed/lightspeed');
			
            foreach ($rowIds as $importId) {               

                try {
                	//Get Lightspeed Data
                	$lsProductArray=$batchModel->getProducts($importId);                	//Save LightSpeed Data
                	$lsProduct=$batchModel->saveProducts($lsProductArray);
                	$messages[]=$lsProduct;
                }
                catch (Exception $e) {
                    $errors[] = $e->getMessage();
                    continue;
                }
                $saved ++;
            }

            $result = array(
                'savedRows' => $saved,
                'errors'    => $errors,
            	'messages'	=> $messages
            );
            $this->getResponse()->setBody(Zend_Json::encode($result));
        }
    }
    
	public function batchRunUpdateAction()
    {
        if ($this->getRequest()->isPost()) {
            $batchId = $this->getRequest()->getPost('batch_id',0);
            $rowIds  = $this->getRequest()->getPost('rows');

            /* @var $batchModel Mage_Dataflow_Model_Batch */

            if (!is_array($rowIds) || count($rowIds) < 1) {
                //exit
                return ;
            }

            $errors = array();
            $messages = array();
            $saved  = 0;
			$batchModel = Mage::getModel('lightspeed/lightspeed');
			
            foreach ($rowIds as $importId) {               

                try {
                	//Get Lightspeed Data
                	$lsProductArray=$batchModel->getProducts($importId);
                	//Save LightSpeed Data
                	$lsProduct=$batchModel->updateProducts($lsProductArray);
                	$messages[]=$lsProduct;
                }
                catch (Exception $e) {
                    $errors[] = $e->getMessage();
                    continue;
                }
                $saved ++;
            }

            $result = array(
                'savedRows' => $saved,
                'errors'    => $errors,
            	'messages'	=> $messages
            );
            $this->getResponse()->setBody(Zend_Json::encode($result));
        }
    }
    
    public function cleanupCategoriesAction()
    {
    	$this->getResponse()->setBody($this->getLayout()->createBlock('lightspeed/cleanup')->toHtml());
        $this->getResponse()->sendResponse();
    	
    }
    
    public function batchCleanupAction()
    {
    	$this->cleanup();
    	$result = array(
                'savedRows' => 1,
                'errors'    => false,
            );
    	$this->getResponse()->setBody(Zend_Json::encode($result));     
    }
    
	public function batchCleanupFinishAction()
    {
    	$result="SUCCESS";
    	$this->getResponse()->setBody(Zend_Json::encode($result));     
    }
    
	public function batchFinishAction()
    {
                
    	$result="SUCCESS";
    	
    	$batchModel = Mage::getModel('lightspeed/lightspeed');
    	
    	//$this->cleanup();
    	
    	Mage::getModel('core/config')->saveConfig('lightspeed/backend/last_import', date('Y-m-d H:i:s') );
    	//Disable Default and Highlight Category
    	
        $this->getResponse()->setBody(Zend_Json::encode($result));      
        
    }
    
    
    private function cleanup()
    {
    	$batchModel = Mage::getModel('lightspeed/lightspeed');
    	if(Mage::getStoreConfig('lightspeed/general/lightspeed_category_handling')!="import"  || Mage::getStoreConfig('lightspeed/general/lightspeed_category_handling')!="master")
    	{    	
    	$cleanup = $batchModel->cleanupCategories();
    	}
    	$cleanupProducts = 0;
    	if(Mage::getStoreConfig('lightspeed/general/lightspeed_product_handling')!="import")
    	{ 
    	$cleanupProducts = $batchModel->cleanupProducts();
    	}
    }
    
	public function batchFinishUpdateAction()
    {
                
    	$result="SUCCESS";
    	
    	//$this->cleanup();
    	
    	Mage::getModel('core/config')->saveConfig('lightspeed/backend/last_update', date('Y-m-d H:i:s') );
    	//Disable Default and Highlight Category
    	
        $this->getResponse()->setBody(Zend_Json::encode($result));      
        
    }
	
	
		
	private function _getConfigurableMasters() {
		
		$sql="SELECT `last_import` FROM lightspeed";
		$result = Mage::getSingleton('core/resource')->getConnection('lightspeed_read')->fetchAll($sql);
		if(!$result[0]['last_import'])	{
			$lastImport="1900-01-01 00:00:01";
		} else {
		$lastImport=$result[0]['last_import'];		
		}
		
		$timeNow=date('Y-m-d H:i:s');
		//$sql="SELECT * FROM  xlsws_product WHERE (master_model = 1) AND (created > '{$lastImport}')";
		$sql="SELECT * FROM  xlsws_product WHERE (master_model = 1) AND (rowid = 2321)";
		$results = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->fetchAll($sql);
		return $results;
		
	}
	
	private function _getConfigurableChildren($masterId) {
		
		$sql="SELECT `last_import` FROM lightspeed";
		$result = Mage::getSingleton('core/resource')->getConnection('lightspeed_read')->fetchAll($sql);
		if(!$result[0]['last_import'])	{
			$lastImport="1900-01-01 00:00:01";
		} else {
		$lastImport=$result[0]['last_import'];		
		}
		
		$timeNow=date('Y-m-d H:i:s');
		$sql="SELECT * FROM  xlsws_product WHERE (master_model = 0) AND (fk_product_master_id = {$masterId}) AND (created > '{$lastImport}')";
		$results = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->fetchAll($sql);
		return $results;
		
	}
	
	
	
	
	
	private function _createConfigurableProduct($lsProduct){
		
	}
	
	private function _createConfigurableChild($lsProduct) {
		
	}
	
	
	public function batchLocalImageAction()
	{
		
	}
	
	
	public function imagesAction()	{
		
		$this->getResponse()->setBody($this->getLayout()->createBlock('lightspeed/images')->toHtml());
        $this->getResponse()->sendResponse();
		
	}
	
	public function batchImageAction()
    {
    	$batchModel = Mage::getModel('lightspeed/lightspeed');
    	$cleanup = $batchModel->importLocalImages();
    	$result = array(
                'savedRows' => $cleanup,
                'errors'    => false
            );
    	$this->getResponse()->setBody(Zend_Json::encode($result));     
    }
    
	public function batchImageFinishAction()
    {
    	$result="SUCCESS";
    	$this->getResponse()->setBody(Zend_Json::encode($result));     
    }
	
	
		
}
	